// fileName      :  logger.go
// createdAt     :  2021-10-07
// description   :	日志

package logger

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"log"
	"os"
	"path/filepath"
	conf "zl-gin/config"
	"zl-gin/utils"
)

var zapLogger *zap.Logger

func getLogLevel() zapcore.Level {
	level := conf.Get().Log.LogLevel
	switch level {
	case "debug":
		return zapcore.DebugLevel
	case "info":
		return zapcore.InfoLevel
	case "warn":
		return zapcore.WarnLevel
	case "error":
		return zapcore.ErrorLevel
	case "dpanic":
		return zapcore.DPanicLevel
	case "panic":
		return zapcore.PanicLevel
	case "fatal":
		return zapcore.FatalLevel

	default:
		return zapcore.DebugLevel
	}
}

func InitLogger() {
	log.Println("init zap logger ...")

	config := conf.Get()

	execDir := utils.GetExecDirectory()
	logPath := execDir + config.Log.LogDir
	utils.CheckDirExistsAndMk(logPath)

	logFile := filepath.Join(logPath, config.Log.FileName)
	log.Println("log file path", logFile)

	file, fileErr := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0777)
	if fileErr != nil {
		log.Panicf("打开日志文件失败, err :%v", fileErr)
	}
	zapcore.AddSync(file)

	//获取日志级别
	level := getLogLevel()

	//根据dev test prd 获取日志配置
	var logConfig zapcore.EncoderConfig
	if config.AppEnv == "prd" {
		logConfig = zap.NewProductionEncoderConfig()
	} else {
		logConfig = zap.NewDevelopmentEncoderConfig()
	}

	output := conf.Get().Log.Output
	if output == "" {
		output = "console"
	}
	if output == "both" {
		//日志输出到文件和控制台
		fileEncoder := zapcore.NewJSONEncoder(logConfig)
		fileCore := zapcore.NewCore(fileEncoder, file, level)

		consoleEncoder := zapcore.NewConsoleEncoder(logConfig)
		consoleCore := zapcore.NewCore(consoleEncoder, os.Stdout, level)

		tee := zapcore.NewTee(fileCore, consoleCore)
		zapLogger = zap.New(tee)

	} else if output == "file" {
		//日志输出到文件
		fileEncoder := zapcore.NewJSONEncoder(logConfig)
		fileCore := zapcore.NewCore(fileEncoder, file, level)

		zapLogger = zap.New(fileCore)
	} else if output == "console" {
		//日志输出到控制台
		consoleEncoder := zapcore.NewConsoleEncoder(logConfig)
		consoleCore := zapcore.NewCore(consoleEncoder, os.Stdout, level)

		zapLogger = zap.New(consoleCore)
	}

	zap.ReplaceGlobals(zapLogger)
}
